package com.zy.qudadid.ui.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.zy.lcpassenger.R;
import com.zy.qudadid.presenter.RegisterPresenter;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.ui.view.RegisterView;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.StringUtil;
import com.zy.qudadid.utils.ToolsUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class NewRegisterActivity extends ToolBarActivity<RegisterPresenter> implements RegisterView {


    @Bind(R.id.etPhone)
    EditText etPhone;
    @Bind(R.id.btnGetVerifyCode)
    TextView btnGetVerifyCode;
    @Bind(R.id.etCode)
    EditText etCode;
    @Bind(R.id.etPass)
    EditText etPass;
    @Bind(R.id.etPassConfirm)
    EditText etPassConfirm;
    @Bind(R.id.chkRule)
    CheckBox chkRule;
    @Bind(R.id.txtRule)
    TextView txtRule;
    @Bind(R.id.txtConfirm)
    TextView txtNext;

    //常量
    private static final String APPKEY = "18b87f9028b7a";
    private static final String APPSECRET = "f88f05a57400bcd8e8a1529f7c92d235";
    private String phoneNumber;
    private String code;

    @Override
    protected CharSequence provideTitle() {
        return "注册";
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_new_register;
    }

    @Override
    public void initListeners() {

    }

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);
        time = new TimeCount(60000, 1000);

        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if(ToolsUtil.isMobileNO(s.toString())){
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_green_4dp);
                    btnGetVerifyCode.setEnabled(true);
                }else{
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
                    btnGetVerifyCode.setEnabled(false);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(ToolsUtil.isMobileNO(s.toString())){
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_green_4dp);
                    btnGetVerifyCode.setEnabled(true);
                }else{
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
                    btnGetVerifyCode.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(ToolsUtil.isMobileNO(s.toString())){
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_green_4dp);
                    btnGetVerifyCode.setEnabled(true);
                }else{
                    btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
                    btnGetVerifyCode.setEnabled(false);
                }
            }
        });

        // 短信验证
        // 初始化短信验证
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handlersms.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh); // 注册短信回调
    }

    /**
     * 获取验证码倒计时
     */
    private TimeCount time;

    //获取验证码的时候避免重复点击
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            btnGetVerifyCode.setText("重新获取验证码");
            btnGetVerifyCode.setClickable(true);
//            btnGetVerifyCode.setEnabled(true);
            btnGetVerifyCode.setBackgroundResource(R.drawable.border_green_4dp);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            btnGetVerifyCode.setClickable(false);//防止重复点击
//            btnGetVerifyCode.setEnabled(false);
//            btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
            btnGetVerifyCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }


    }

    @Override
    public RegisterPresenter createPresenter() {
        return new RegisterPresenter();
    }


    @OnClick({R.id.btnGetVerifyCode, R.id.txtRule, R.id.txtConfirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnGetVerifyCode:
                phoneNumber = etPhone.getText().toString();

                sendMessageCode();
                break;
            case R.id.txtRule:
                //TODO 跳转协议
                break;
            case R.id.txtConfirm:
                pass = etPass.getText().toString();
                code = etCode.getText().toString();

                if(!TextUtils.isEmpty(phoneNumber)){
                    if(!TextUtils.isEmpty(code)){
                        if(!TextUtils.isEmpty(pass)){
                            if(pass.equals(etPassConfirm.getText().toString())) {
                                if(chkRule.isChecked()) {
                                    SMSSDK.submitVerificationCode("86", phoneNumber, code);
                                }else{
                                    toast("请勾选同意协议");
                                }
                            }else{
                                toast("两次密码必须一致");
                            }
                        }else{
//                            Toast.makeText(RegisterActivity.this,,Toast.LENGTH_SHORT).show();
                            toast("请输入密码");
                        }
                    }else{
//                        Toast.makeText(RegisterActivity.this,"请输入验证码",Toast.LENGTH_SHORT).show();
                        toast("请输入验证码");
                    }
                }else{
//                    Toast.makeText(RegisterActivity.this,"请输入手机号",Toast.LENGTH_SHORT).show();
                    toast("请输入手机号");
                }

                break;
        }
    }

    String pass;


    /**
     *手机发送验证码
     */
    public void sendMessageCode() {
//        btnGetVerifyCode.setText(""+TIME_INIT+"秒后可重发");
        btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
//        time=TIME_INIT;
//        handler.postDelayed(runnabletime, 1000);
        SMSSDK.getVerificationCode("86", phoneNumber);
    }

    /**
     * 创建可调用ui的handler
     */
    Handler handlersms = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;

            if (result == SMSSDK.RESULT_COMPLETE) {
                // 回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    // 提交验证码成功
                    Map map = new HashMap();
                    map.put("tel", phoneNumber);
                    map.put("type", 1+"");
                    map.put("pwd", pass);
                    map.put("username", phoneNumber);
                    String json = StringUtil.toJson(map);
                    try {
                        String data1 = AESCrypt.getInstance().encrypt(json);
                        String d = StringUtil.replaceBlank(data1);
//                        presenter.register(d);
                    } catch (Exception ex) {
                    }

//                    finish();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    // 获取验证码成功
                    time.start();//开始计时
                    toast("发送成功");
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    // 返回支持发送验证码的国家列表
                }
            } else {
                try {
                    snb(event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证过于频繁，请稍后再试" : "验证码错误",btnGetVerifyCode);
                }catch (Exception ex){}
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        handler.removeCallbacks(runnabletime);
        SMSSDK.unregisterAllEventHandler();
    }


//    @Override
//    public void success() {
//        toast("注册成功");
//        Map map = new HashMap();
//        map.put("tel", phoneNumber);
//        map.put("pwd", pass);
//        String json = StringUtil.toJson(map);
//        try {
//            String data1 = AESCrypt.getInstance().encrypt(json);
//            String d = StringUtil.replaceBlank(data1);
//    //        presenter.login(d);
//        } catch (Exception ex) {
//
//        }
//    }

//    @Override
//    public void error(String str) {
//        toast(str);
//    }

    @Override
    public void registerSuccess() {

    }

    @Override
    public void registerError(String str) {

    }

    @Override
    public void loginSuccess() {
        finish();
    }

    @Override
    public void loginError(String str) {
        toast(str);
    }

    @Override
    public void exception() {

    }
}
